<template>
  <div style="width: 60%;margin: 0 auto" v-if="info.id">
    <el-card v-if="info.id">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="magnifier-container">
            <div class="preview-image" 
                 ref="previewContainer"
                 @mousemove="handleMouseMove"
                 @mouseenter="handleMouseEnter"
                 @mouseleave="handleMouseLeave">
              <img :src="currentImage" ref="sourceImage" alt="商品图片"/>
              <div class="magnifier" 
                   v-show="showMagnifier"
                   :style="magnifierStyle"></div>
            </div>
            <div class="zoomed-view" 
                 v-show="showMagnifier"
                 ref="zoomedView">
              <canvas ref="zoomCanvas"></canvas>
            </div>
          </div>
          <div class="thumbnail-list">
            <div v-for="(img, index) in info.imgList.split(',')" 
                 :key="index"
                 class="thumbnail-item"
                 :class="{ active: currentImageIndex === index }"
                 @click="changeImage(index)">
              <el-image :src="img" fit="cover"/>
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <el-space direction="vertical" alignment="left" style="width: 100%">
            <div>
              <H2>{{ info.name }} </H2>
            </div>
            <div style="font-size: 24px">
              <span>价格:</span>
              <span style="color: red">￥{{ info.price }} </span>
            </div>
            <div>
              <el-space size="large">
                <el-statistic title="库存" :value="info.stock"/>
                <el-statistic title="销量" :value="info.salesVolume"/>
              </el-space>
            </div>
            <div>
              <el-space direction="vertical" alignment="left">
                <el-space spacer="|">
                  <el-tag type="success">准时达</el-tag>
                  <span>承诺24小时内发货，超时必赔</span>
                </el-space>
                <el-space spacer="|">
                <span>
                    <el-icon :size="18" color="green"><CircleCheck/></el-icon> 7天价保</span>
                  <span>买贵双倍赔</span>
                </el-space>

                <el-space spacer="|">
                  <span>包邮</span>
                  <span>免费上门退换</span>
                  <span>破损包退换</span>
                  <span>上门换新</span>
                </el-space>
              </el-space>
            </div>
            <div>
              <el-button type="danger" @click="buy">立即购买</el-button>
              <el-button type="info" @click="removeCollect" v-if="info.productCollectId">取消收藏</el-button>
              <el-button type="warning" @click="addCollect" v-if="!info.productCollectId">收藏</el-button>
              <el-button type="primary" @click="addShoppingCart">加入购物车</el-button>
            </div>
          </el-space>
        </el-col>
      </el-row>

      <el-divider></el-divider>
      <Shop :shopId="info.shopId"></Shop>

      <el-divider></el-divider>
      <el-tabs v-model="activeName">
        <el-tab-pane label="图文详情" name="first">
          <div class="content" v-html="info.intro" style="  margin: 0 auto; width: 75%;"></div>
        </el-tab-pane>
        <el-tab-pane label="评价" name="second">
          <ProductOrderEvaluate :productId="info.id"/>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
        v-model="buyDialogOpen"
        v-if="buyDialogOpen"
        title="填写订单信息"
        width="500"
    >
      <el-form ref="buyFormRef" :model="productOrder" label-width="100px">
        <slot name="content">
          <el-form-item label="收货地址" prop="shippingAddressId"
                        :rules="[{required:true,message:'请输入选择地址',trigger:[ 'blur','change']}]">
            <el-select v-model="productOrder.shippingAddressId" placeholder="请选择" filterable>
              <el-option :label="item.name+'_'+item.tel+'_'+item.address" :value="item.id" :key="item.id"
                         v-for="item in shippingAddressList"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="quantity"
                        :rules="[{required:true,message:'请输入购买数量',trigger:[ 'blur','change']}]">
            <el-input-number v-model="productOrder.quantity" :min="1"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="5" v-model="productOrder.remark"></el-input>
          </el-form-item>
        </slot>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="buySubmit" :icon="Check">提交</el-button>
          <el-button @click="buyDialogOpen=false" :icon="Close">取消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>
<script setup>
import request from "@/utils/http.js";
import {ref, toRaw, onMounted, computed} from "vue";
import {useRoute} from "vue-router";
import {Check, Close} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import ProductOrderEvaluate from "@/components/ProductOrderEvaluate.vue";
import Shop from "@/components/Shop.vue";


const route = useRoute()
const id = ref(route.params.id)
const info = ref({});

// 放大镜相关
const currentImageIndex = ref(0)
const currentImage = computed(() => {
  if (!info.value.imgList) return ''
  const images = info.value.imgList.split(',')
  return images[currentImageIndex.value]
})

const showMagnifier = ref(false)
const magnifierStyle = ref({
  left: '0px',
  top: '0px'
})

const previewContainer = ref(null)
const sourceImage = ref(null)
const zoomCanvas = ref(null)
const zoomedView = ref(null)

const MAGNIFIER_SIZE = 100 // 放大镜框的大小
const ZOOM_LEVEL = 2.5 // 放大倍数

function changeImage(index) {
  currentImageIndex.value = index
}

function handleMouseEnter() {
  showMagnifier.value = true
}

function handleMouseLeave() {
  showMagnifier.value = false
}

function handleMouseMove(e) {
  if (!previewContainer.value || !sourceImage.value || !zoomCanvas.value) return

  const rect = previewContainer.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top

  // 更新放大镜框位置
  let magnifierX = x - MAGNIFIER_SIZE / 2
  let magnifierY = y - MAGNIFIER_SIZE / 2

  // 限制放大镜框在图片范围内
  magnifierX = Math.max(0, Math.min(magnifierX, rect.width - MAGNIFIER_SIZE))
  magnifierY = Math.max(0, Math.min(magnifierY, rect.height - MAGNIFIER_SIZE))

  magnifierStyle.value = {
    left: `${magnifierX}px`,
    top: `${magnifierY}px`
  }

  // 绘制放大的图像
  const canvas = zoomCanvas.value
  const ctx = canvas.getContext('2d')
  
  // 设置canvas尺寸为放大区域的大小
  canvas.width = zoomedView.value.offsetWidth
  canvas.height = zoomedView.value.offsetHeight

  // 计算源图像上对应的区域
  const sourceX = (magnifierX / rect.width) * sourceImage.value.naturalWidth
  const sourceY = (magnifierY / rect.height) * sourceImage.value.naturalHeight
  const sourceWidth = (MAGNIFIER_SIZE / rect.width) * sourceImage.value.naturalWidth
  const sourceHeight = (MAGNIFIER_SIZE / rect.height) * sourceImage.value.naturalHeight

  // 清除之前的内容
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 绘制放大的图像
  ctx.drawImage(
    sourceImage.value,
    sourceX, sourceY,
    sourceWidth, sourceHeight,
    0, 0,
    canvas.width, canvas.height
  )
}

getInfo()

function getInfo() {
  request.get("/product/selectById/" + id.value).then(res => {
    info.value = res.data;
  })
}


const shippingAddressList = ref([])
getShippingAddressList();

async function getShippingAddressList() {
  let data = {
    pageNum: 1,
    pageSize: 100
  }
  request.get("/shippingAddress/page", {
    params: data
  }).then(res => {
    shippingAddressList.value = res.data.list;
  })
}

addBrowsingHistory();

/**
 * 添加浏览历史
 */
function addBrowsingHistory() {
  request.post("/productBrowsingHistory/add", {productId: id.value}).then(res => {

  })
}

function addCollect() {
  request.post("/productCollect/add", {productId: id.value}).then(res => {
    info.value.productCollectId = res.data.id
  })
}


function removeCollect() {
  let ids = [
    info.value.productCollectId
  ]
  request.delete("/productCollect/delBatch", {data: ids}).then(res => {
    info.value.productCollectId = null
  })
}


function addShoppingCart() {
  request.post("/shoppingCart/add", {productId: id.value, quantity: 1}).then(res => {
    ElMessage({
      message: "添加成功",
      type: 'success'
    });
  })
}


const buyDialogOpen = ref(false)
const productOrder = ref({})
const buyFormRef = ref()

function buy() {
  productOrder.value = {}
  productOrder.value.quantity = 1
  buyDialogOpen.value = true
}

function buySubmit() {
  buyFormRef.value.validate((valid) => {
    if (!valid) {
      ElMessage({
        message: "验证失败，请检查表单!",
        type: 'warning'
      });
      return
    }
    let shippingAddress = shippingAddressList.value.find(item => item.id == productOrder.value.shippingAddressId);
    productOrder.value.consigneeName = shippingAddress.name;
    productOrder.value.consigneeTel = shippingAddress.tel;
    productOrder.value.consigneeAddress = shippingAddress.address;
    productOrder.value.productId = id.value;
    request.post("/productOrder/add", productOrder.value).then(res => {
      if (!res) {
        return
      }
      buyDialogOpen.value = false
      ElMessage({
        message: "操作成功",
        type: 'success'
      });
      router.push("/front/productOrder")
    })
  })
}

const activeName = ref('first')


</script>

<style scoped>
/* 使用 ::v-deep 穿透作用域 */
::v-deep .content img {
    width: 100%;
}

.magnifier-container {
  position: relative;
  width: 100%;
  margin-bottom: 10px;
}

.preview-image {
  position: relative;
  width: 100%;
  height: 300px;
  overflow: hidden;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.magnifier {
  position: absolute;
  width: 100px;
  height: 100px;
  border: 2px solid #e1251b;
  background-color: rgba(255, 255, 0, 0.2);
  cursor: move;
  pointer-events: none;
}

.zoomed-view {
  position: absolute;
  left: 105%;
  top: 0;
  width: 300px;
  height: 300px;
  border: 1px solid #ddd;
  overflow: hidden;
  background-color: #fff;
  z-index: 100;
}

.zoomed-view canvas {
  width: 100%;
  height: 100%;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.thumbnail-item {
  width: 60px;
  height: 60px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail-item:hover {
  border-color: #e1251b;
}

.thumbnail-item.active {
  border-color: #e1251b;
}

.thumbnail-item .el-image {
  width: 100%;
  height: 100%;
}
</style>
